class_name StateMachine
extends Node

@onready var characterCtrl: CharacterController = $".."


#当前状态
var curState: IState = null

var curStateType: CharacterStates = CharacterStates.IDEL

#状态类型和状态的映射
var stateTypeIStateMap: Dictionary = Dictionary()


enum CharacterStates {IDEL, RUN, JUMP, FALL, COMBO,POST_ROCK, UNKNOW}

#region 生命周期


# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	if characterCtrl != null:
		# print("StateMachine - 角色控制器初始化完毕")
		pass
	#初始化状态
	init_states()
	#切换状态
	switch_character_state(curStateType)
	

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if curState:
		curState.logic_update(delta)


func _physics_process(delta: float) -> void:
	if curState:
		curState.physics_update(delta)


#endregion

#初始化状态
func init_states() -> void:
	var idelState = IdelState.new()
	idelState.init(characterCtrl, self)
	stateTypeIStateMap[CharacterStates.IDEL] = idelState

	var runState = RunState.new()
	runState.init(characterCtrl, self)
	stateTypeIStateMap[CharacterStates.RUN] = runState

	stateTypeIStateMap[CharacterStates.JUMP] = JumpState.new()
	stateTypeIStateMap[CharacterStates.JUMP].init(characterCtrl, self)


	stateTypeIStateMap[CharacterStates.FALL] = FallState.new()
	stateTypeIStateMap[CharacterStates.FALL].init(characterCtrl, self)

	stateTypeIStateMap[CharacterStates.COMBO] = ComboState.new()
	stateTypeIStateMap[CharacterStates.COMBO].init(characterCtrl, self)


	stateTypeIStateMap[CharacterStates.POST_ROCK] = PostRockState.new()
	stateTypeIStateMap[CharacterStates.POST_ROCK].init(characterCtrl, self)

	# print("stateTypeIStateMap === ", stateTypeIStateMap)
	

#状态切换
func switch_state(newState: IState) -> bool:
	if newState == null:
		print("新状态为空")
		return false
	if curState == null:
		newState.enter()
		curState = newState
		return true
	if curState.get_priority() > newState.get_priority():
		return false
	curState.exit()
	newState.enter()
	curState = newState
	return true

func switch_character_state(newStateType: CharacterStates) -> bool:
	var newState = stateTypeIStateMap[newStateType]
	if newState:
		var switchRes: bool = switch_state(newState)
		if switchRes:
			curState = newState
		return switchRes
	print("新状态为空")
	return false
